package org.libjpopup.receiver;

import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;

import javax.swing.*;
import java.io.IOException;

public class Receiver {

    private JpcapCaptor jpcapCaptor;


    public static String getMyHostname() {
        return myHostname;
    }

    public static String getMyIp() {
        return myIp;
    }

    private static String myIp;
    private static String myHostname;

    public Receiver() throws IOException {
        init("");
    }


    public static void main(String[] args) throws IOException {
        Receiver r = new Receiver();
        r.start(new ConsolePopupReceiver());
    }

    public Receiver(String myHostname) throws IOException {
        init(myHostname);
    }

    private void init(String localhost) throws IOException {
        myHostname = localhost;
        for (NetworkInterface iface : JpcapCaptor.getDeviceList()) {
            if (!iface.loopback) {
                for (NetworkInterfaceAddress address : iface.addresses)
                    if (address.address != null && address.address.getHostAddress().startsWith("10.")) {
                        jpcapCaptor = JpcapCaptor.openDevice(iface, 1024, false, 500);
                        jpcapCaptor.setFilter("(udp port 138) and (dst net " + address.broadcast.getHostAddress() + " or " + address.address.getHostAddress() + ")", true);
                        myIp = address.address.getHostAddress();
                    }
            }
        }
        if (jpcapCaptor == null)//interface at 10.* not found; try to check 192.168.*
            for (NetworkInterface iface : JpcapCaptor.getDeviceList()) {
                if (!iface.loopback) {
                    for (NetworkInterfaceAddress address : iface.addresses)
                        if (address.address != null && address.address.getHostAddress().startsWith("192.168.")) {
                            jpcapCaptor = JpcapCaptor.openDevice(iface, 1024, false, 500);
                            jpcapCaptor.setFilter("(udp port 138) and (dst net " + address.broadcast.getHostAddress() + " or " + address.address.getHostAddress() + ")", true);
                            myIp = address.address.getHostAddress();
                        }
                }
            }
        if (jpcapCaptor != null)
            System.out.println("init success!");
    }

    public void start(PopupReceiverIF receiver) {
        if (jpcapCaptor == null) {
//            new JOptionPane("failed to find interface binded to 10.*.*.*! Possibly you don't have enough permissions", JOptionPane.ERROR_MESSAGE);
            System.err.println("failed to find interface binded to 10.*.*.* or 192.168.*.*! Possibly you don't have enough permissions");
            System.exit(1);
        }
        jpcapCaptor.loopPacket(-1, new PacketReceiverImpl(receiver));
    }

    public void stop() {
        jpcapCaptor.breakLoop();
        jpcapCaptor.close();
    }
}
